# coding: utf-8
'''
  M5Paper老黄历项目

  为老黄历项目提供JSON数据API接口，在 M5Paper 的电子墨水屏上，呈现老黄历界面和信息

  作者：HonestQiao
  日期：2024-01-10
  版本：v1.0
'''

from flask import Flask, Response, jsonify, request, make_response, render_template, send_from_directory, abort
from flask import g
import requests
import datetime
import re
import json
import os
import sys

SERVER_PORT = 8889

# 初始化Flask
app = Flask(__name__)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/')
def index():
    return "Hello, World!"

@app.route('/api/v1.0/laohuangli/index/<direction>/<index>', methods=['GET','POST'])
def api_test(direction='next',index=0):
    if index.isnumeric():
        index = int(index)
    else:
        index = 0

    if direction == 'prev' and index>0:
        index = -index
    else:
        direction == 'next'

    if index>0:
        index_diff_day = "%d天后 " % abs(index)
    elif index<0:
        index_diff_day = "%d天前 " % abs(index)
    else:
        index_diff_day = "今天"

    now = datetime.datetime.now()
    day_index = now + datetime.timedelta(days = index)
    day_ymd = day_index.strftime('%Y%m%d')
    day_file = 'caches/%s.json' % day_ymd
    if os.path.exists(day_file):
        print("read %s from cache" % day_file)
        s = ""
        with open(day_file, "r") as f:
            s = f.read()
            f.close()
        s = str(s).replace('__间隔天数__', index_diff_day)
        return Response(str(s), mimetype='application/json')
    else:
        print("没有老黄历数据")
        return Response(status="404", mimetype='application/json')
        sys.exit()

# 启动RESTFul
app.run(
    host = '0.0.0.0',
    port = SERVER_PORT,
    debug = True
)
print("网络服务启动完成")